<template>
  <div class="home">
    <div class="home_map" id="homeMapContainer" tabindex="0"></div>
    <el-dialog
      title="设备轨迹"
      :visible.sync="equipmentLineDialogFlag"
      width="80%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div class="dialog_bg">
        <div class="dialog_map" id="homeLineMapContainer" tabindex="0"></div>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import utils from '../utils/utils'
import mVue from 'vue';
import eventBus from '../utils/eventBus'
export default {
  name: 'home',
  components: {},
  data () {
    return {
      username: '',
      ws: null,
      eqList: [],
      eqList1: [],
      eqList2: [],
      allCount: '',
      workCount: '',
      alertCount: '',
      stopCount: '',
      faultCount: '',
      map: null,
      disProvince: null,
      fixedMarkerList: [],
      infoWindow: null,
      fixedMarkers: [],
      equipmentLineDialogFlag: false,
      lineMap: null
    }
  },
  created() {
    this.initWebsocket()
  },
  mounted() {

  },
  methods: {
    initWebsocket() {
      let _this = this
      _this.username = localStorage.getItem('username')
      if ('WebSocket' in window) {
        // 打开一个 web socket
        let ws = new WebSocket(process.env.PROGOO_SOCKET + `ws/${_this.username}`)
        _this.ws = ws
        // let ws = new WebSocket(`ws://39.98.121.176:32766/?${key}&${time}`);
        ws.onopen = function() {
          // Web Socket 已连接上，使用 send() 方法发送数据
          // _this.$message({
          //   message: '设备通讯连接成功',
          //   type: 'success'
          // });
        }
        ws.onmessage = function(evt) {
          try {
            let msg = JSON.parse(evt.data)
            _this.websocketMsgHandle(msg)
          } catch (error) {
            console.log('不是个json对象')
          }
        }
        ws.onclose = function() {
          // 关闭 websocket
        }
        ws.onerror = function() {
          _this.$message.error('设备通讯连接已断开')
        }
      } else {
        // 浏览器不支持 WebSocket
        alert('您的浏览器不支持 WebSocket!')
      }
    },
    websocketMsgHandle(msg) {
      console.log(msg)
      if(msg.type === 17) {
        this.allCount = msg.all_count
        this.workCount = msg.work_count
        this.alertCount = msg.alert_count
        this.stopCount = msg.stop_count
        this.faultCount = msg.fault_count

        this.eqList = msg.fixed_type_list
        this.initMapInfo(msg)
      }
    },
    getEquipAreaCodeList(type) {
      let codeList = []
      if(type === 'fixed') {
        for(let i in this.eqList) {
          codeList.push(this.eqList[i].area_code)
        }
        // for(let i in this.eqList1) {
        //   codeList.push(this.eqList1[i].area_code)
        // }
        // for(let i in this.eqList2) {
        //   codeList.push(this.eqList2[i].area_code)
        // }
      }
      return codeList
    },
    initMapInfo(data) {
      let depth = 2
      if(this.map) {
        this.map.setCenter(data.center)
      }else {
        this.map = new AMap.Map('homeMapContainer', {
          zoom: 9,
          resizeEnable: true,
          center: data.center,
          pitch: 0,
          viewMode: '3D',
          mapStyle: 'amap://styles/fresh'
        })
      }
      this.map.on('click', this.mapClickListener);
      let adCode = this.getEquipAreaCodeList('fixed')
      this.initProvince(adCode, depth)
      this.drawEquipOnMap()
    },
    mapClickListener() {
      if(this.infoWindow){
        this.infoWindow.close()
      }
    },
    initProvince(code, dep) {
      dep = typeof dep === 'undefined' ? 2 : dep
      this.disProvince && this.disProvince.setMap(null)
      this.disProvince = new AMap.DistrictLayer.Province({
        zIndex: 12,
        adcode: code,
        depth: typeof dep === 'undefined' ? 2 : dep,
        styles: {
          'fill': 'rgba(1,68,112,0.6)',
          'province-stroke': '#05F8F9',
          'city-stroke': '#501BC2', // 中国地级市边界
          'county-stroke': '#05F8F9' // 中国区县边界
        }
      })
      this.disProvince.setMap(this.map)
    },
    drawEquipOnMap() {
      let that = this
      that.fixedMarkerList = []
      that.fixedMarkers = []
      let circleList = []
      that.map.clearMap() // 清除地图覆盖物
      for(let i in that.eqList) {
        for(let j in that.eqList[i].list) {
          let itemLongitude
          let itemLatitude
          if(Object.keys(that.eqList[i].list[j].gps_array).length > 0 && that.eqList[i].list[j].gps_array.longitude) {
            itemLongitude = that.eqList[i].list[j].gps_array.longitude
            itemLatitude = that.eqList[i].list[j].gps_array.latitude
          }else {
            itemLongitude = that.eqList[i].list[j].alert.longitude
            itemLatitude = that.eqList[i].list[j].alert.latitude
          }
          let distance = that.getDistanceFromTwoPoint(itemLatitude,itemLongitude,that.eqList[i].list[j].alert.latitude, that.eqList[i].list[j].alert.longitude)
          let iconImg = ''
          let markerZIndex = 100
          if(distance > that.eqList[i].list[j].alert.radius) {
            //未选中，报警
            iconImg = process.env.PROGOO_IMAGE + 'thumbtack/blue_warn.png'
          }else {
            //未选中，未报警
            iconImg = process.env.PROGOO_IMAGE + 'thumbtack/blue.png'
          }
          let icon = new AMap.Icon({
            size: new AMap.Size(30, 30),    // 图标尺寸
            image: iconImg,  // Icon的图像
            imageOffset: new AMap.Pixel(0, 0),  // 图像相对展示区域的偏移量，适于雪碧图等
            imageSize: new AMap.Size(30, 30),   // 根据所设置的大小拉伸或压缩图片
          });
          let marker = new AMap.Marker({
            position: new AMap.LngLat(itemLongitude, itemLatitude),
            title: that.eqList[i].list[j].id + '_0',
            icon: icon,
            anchor:'bottom-center',
            offset: new AMap.Pixel(0,0),
            zIndex: markerZIndex
          });
          that.fixedMarkers.push(that.eqList[i].list[j].id)
          that.fixedMarkerList.push(marker)

          //marker 点击时打开
          marker.on('click', function(e) {
            that.openEquitInfoOnMap(e.target.w.title,marker);
          });
          let circle = new AMap.Circle({
            center: new AMap.LngLat(that.eqList[i].list[j].alert.longitude, that.eqList[i].list[j].alert.latitude),  // 圆心位置
            radius: that.eqList[i].list[j].alert.radius, // 圆半径
            fillColor: '#FFB6C1',   // 圆形填充颜色
            fillOpacity: 0.4,
            strokeStyle: 'dashed',
            strokeColor: 'red', // 描边颜色
            strokeWeight: 1, // 描边宽度
          });
          circleList.push(circle)
          // that.map.add(circle);
        }
      }
      that.map.add(that.fixedMarkerList)
      that.map.add(circleList);
    },
    openEquitInfoOnMap(eId,marker) {
      let eqId = utils.getStrByUnderlineBefore(eId)
      let type = utils.getStrByUnderlineAfter(eId)
      let equipmentList = []
      switch (type) {
        case "0":
          equipmentList = this.eqList
          break;
        case "1":
          equipmentList = this.eqList1
          break;
        case "2":
          equipmentList = this.eqList2
          break;

        default:
          break;
      }
      for(let i in equipmentList) {
        for(let j in equipmentList[i].list) {
          if(equipmentList[i].list[j].id === eqId) {
            var MyComponent = mVue.extend({
              data: function () {
                return {
                }
              },
              props:['pLData'],
              template: `<div class="szEquipInfo_bg">
                          <div class="szEquipInfo_title">
                            <div class="szEquipInfoTitle_sign"></div>
                            <div class="szEquipInfoTitle_text">设备信息 <span @click="openEquipLine" style="color: #FFE400;cursor: pointer;font-size: 13px">（查看轨迹）</span></div>
                          </div>
                          <div class="szEquipInfo_infoArea">
                            <div class="szEquipInfo_infoAreaScrollBg">
                              <div class="szEquipInfo_infoRow">
                                <div class="szEquipInfo_infoItem" style="padding-left:70px;text-indent: -70px;">设备名称：<span style="color: #FFE400">{{ pLData.equipment_name }}</span></div>
                                <div v-if="pLData.on_type == '4'" class="szEquipInfo_infoItem" style="padding-left:70px;text-indent: -70px">运行状态：<span style="color:#FE5325">报警</span></div>
                                <div v-else-if="pLData.on_type == '1'" class="szEquipInfo_infoItem" style="padding-left:70px;text-indent: -70px">运行状态：<span style="color:#13FB5F">在线</span></div>
                                <div v-else-if="pLData.on_type == '2'" class="szEquipInfo_infoItem" style="padding-left:70px;text-indent: -70px">运行状态：<span style="color:#96CAD4">调试</span></div>
                                <div v-else-if="pLData.on_type == '3'" class="szEquipInfo_infoItem" style="padding-left:70px;text-indent: -70px">运行状态：<span style="color:#EDA33A">维修</span></div>
                              </div>
                              <div class="szEquipInfo_infoRow">
                                <div class="szEquipInfo_infoItem" style="padding-left:70px;text-indent: -70px;">设备版本：<span style="color: #FFE400">{{ pLData.version ? pLData.version : '-' }}</span></div>
                                <div class="szEquipInfo_infoItem" style="padding-left:70px;text-indent: -70px;">请求次数：<span style="color: #FFE400">{{ pLData.sort_code }}次</span></div>
                              </div>
                              <div class="szEquipInfo_infoRow">
                                <div class="szEquipInfo_infoItem" style="padding-left:84px;text-indent: -84px;">设备负责人：<span style="color: #FFE400">{{ pLData.user_name }}</span></div>
                                <div class="szEquipInfo_infoItem" style="padding-left:70px;text-indent: -70px;">电池电量：<span style="color: #FFE400">{{ pLData.electricity ? pLData.electricity + '%' : '-' }}</span></div>
                              </div>
                              <div class="szEquipInfo_infoRow">
                                <div class="szEquipInfo_infoItem" style="width:100%;padding-left:84px;text-indent: -84px;">设备序列号：<span style="color: #FFE400">{{ pLData.model }}</span></div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>`,
              mounted() {

              },
              methods:{
                openEquipLine: function() {
                  eventBus.$emit("equipLine",this.pLData)
                }
              }
            });
            var component = new MyComponent({
              propsData: {
                  pLData: equipmentList[i].list[j],
              }
            }).$mount()
            // new MyComponent().$mount();
            this.infoWindow = new AMap.InfoWindow({
              isCustom: true,  //使用自定义窗体
              content: component.$el,
              //基点指向marker的头部位置
              offset: new AMap.Pixel(0, -31)
            });
            this.infoWindow.open(this.map, marker.getPosition());
            this.infoWindow.on('open',this.infoWindowOpen('open'))

            return
          }
        }
      }
    },
    infoWindowOpen(e) {
      eventBus.$on("equipLine", item => {
        this.equipmentLineDialogFlag = true
        this.$fetch({
          url: process.env.PROGOO_GATE_WATER + 'admin/equipment/trajectory',
          method: "post",
          data: {
            id: item.id
          }
        }).then(res => {
          if (res.data.code === 200) {
            let mapCenter = []
            if(res.data.result.length > 0 && res.data.result[0].latitude && res.data.result[0].latitude !== ''){
              mapCenter.push(res.data.result[0].longitude)
              mapCenter.push(res.data.result[0].latitude)
            }else {
              mapCenter.push(item.alert.longitude)
              mapCenter.push(item.alert.latitude)
            }
            this.lineMap = new AMap.Map('homeLineMapContainer', {
                zoom: 9,
                center: mapCenter,
                resizeEnable: true,
                pitch: 0,
                viewMode: '3D',
                mapStyle: 'amap://styles/fresh'
            });

            var lineArr = []
            let dataLength = 0
            if(res.data.result.length > 200) {
              dataLength = 200
            }else {
              dataLength = res.data.result.length
            }
            for(let i = 0;i < dataLength; i++) {
              let pointArr = []
              if(res.data.result[i].latitude && res.data.result[i].latitude !== '') {
                pointArr.push(parseFloat(res.data.result[i].longitude))
                pointArr.push(parseFloat(res.data.result[i].latitude))
                lineArr.push(pointArr)
              }
            }
            var polyline = new AMap.Polyline({
              map: this.lineMap,
              path: lineArr,
              strokeColor: "#00A",  //线颜色
              strokeOpacity: 1,     //线透明度
              strokeWeight: 3,      //线宽
              strokeStyle: "solid"  //线样式
            });
            this.lineMap.setFitView();
            let circle = new AMap.Circle({
              center: new AMap.LngLat(item.alert.longitude, item.alert.latitude),  // 圆心位置
              radius: item.alert.radius, // 圆半径
              fillColor: 'red',   // 圆形填充颜色
              fillOpacity: 0.4,
              strokeStyle: 'dashed',
              strokeColor: '#fff', // 描边颜色
              strokeWeight: 1, // 描边宽度
            });
            this.lineMap.add(circle);

            // var polyline = new AMap.Polyline({
            //     path: lineArr,          //设置线覆盖物路径
            //     strokeColor: "#FF0000", //线颜色
            //     strokeOpacity: 2,       //线透明度
            //     strokeWeight: 2,        //线宽
            //     strokeStyle: "solid",   //线样式
            //     strokeDasharray: [10, 5] //补充线样式
            // });
            // polyline.setMap(this.lineMap);

          }else {
            this.$notify.error({
              title: '错误',
              message: res.data.message
            });
          }
        })

      })
    },
    getDistanceFromTwoPoint(lat1, lng1, lat2, lng2) {
      let radLat1 = lat1*Math.PI / 180.0;
      let radLat2 = lat2*Math.PI / 180.0;
      let a = radLat1 - radLat2;
      let b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
      let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
      Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
      s = s *6378.137 ;// EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000;
      return s * 1000;
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.home{
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  .home_map {
    width: 100%;
    height: 100%
  }
  .dialog_bg {
    width: 100%;
    height: 600px;
    .dialog_map {
      width: 100%;
      height: 100%;
    }
  }
}
.szEquipInfo_bg {
  /* border-radius: 5px;
  border: 1px solid #07a;
  background: #153050; */
  padding-left: 10px;
  padding-bottom: 10px;
  width: 350px;
  height: 222px;
  float: left;
  background: url('~@/assets/images/equiptmentInfo_bg.png');
  background-size: 100% 100%
}
.szEquipInfo_title {
  width: 100%;
  line-height: 48px;
  height: 48px;
  text-align: center;
  color: #fff;
  font-size: 15px;
  float: left;
  box-sizing: border-box;
  padding-right: 10px;
}
.szEquipInfoTitle_sign {
  width: 4px;
  background: #00FFFC;
  height: 18px;
  float: left;
  margin: 18px 6px 0 12px;
}
.szEquipInfoTitle_text {
  float: left;
  height: 100%;
  text-align: left;
  box-sizing: border-box;
  padding-top: 3px;
}
/* .szEquipInfo_closeBtn {
  width: 46px;
  height: 46px;
  line-height: 46px;
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.szEquipInfo_closeBtn >i {
  color: #fff;
  font-size: 16px;
} */
.szEquipInfo_infoArea {
  width: 100%;
  float: left;
  height: 160px;
  box-sizing: border-box;
  padding: 0 10px 0 10px;
}
.szEquipInfo_infoAreaScrollBg {
  width: 100%;
  float: left;
  height: 100%;
  padding-right: 10px;
  box-sizing: border-box;
  overflow-y: scroll;
}
.szEquipInfo_infoAreaScrollBg::-webkit-scrollbar{
  width: 2px;
  background: #007acc;
}
.szEquipInfo_infoAreaScrollBg::-webkit-scrollbar-thumb {
  border-radius: 3px;
  height: 100px;
  background-color: #ccc;
}

.szPointList_infoArea {
  width: 100%;
  float: left;
  height: 158px;
  box-sizing: border-box;
  padding: 0 12px 0 4px;
}
.szPointList_infoAreaBg {
  width: 100%;
  height: 100%;
  float: left;
  overflow-y: scroll;
}
.szPointList_infoAreaBg::-webkit-scrollbar{
  width: 2px;
  background: #007acc;
}
.szPointList_infoAreaBg::-webkit-scrollbar-thumb {
  border-radius: 3px;
  height: 100px;
  background-color: #ccc;
}
.szEquipInfo_infoRow {
  width: 100%;
  float: left;
  border-bottom: 1px solid #0E6083;
}
.szEquipInfo_infoItem {
  width: 50%;
  box-sizing: border-box;
  color: #96CAD4;
  font-size: 14px;
  padding: 10px 10px 10px 0;
  float: left;
  word-break: break-all;
}
.szPointList_pointItem {
  width: 100%;
  box-sizing: border-box;
  color: #0efcff;
  font-size: 13px;
  padding: 5px 10px 5px 0;
  float: left;
  display: flex;
}
.szPointList_pointItemIcon {
  width: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.szPointList_pointItemText {
  flex: 1;
}
</style>
